package com.tompai.server.listener;

import java.io.File;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tompai.printer.Printer;
import com.tompai.server.util.ConfigureReader;
import com.tompai.server.util.FileBlockUtil;

@WebListener
public class SCListener implements ServletContextListener {
	public void contextInitialized(final ServletContextEvent sce) {
		Printer.instance.print("文件系统节点信息校对...");
		final String fsp = ConfigureReader.instance().getFileSystemPath();
		final File fspf = new File(fsp);
		if (fspf.isDirectory() && fspf.canRead() && fspf.canWrite()) {
			final ApplicationContext context = (ApplicationContext) WebApplicationContextUtils
					.getWebApplicationContext(sce.getServletContext());
			final FileBlockUtil fbu = context.getBean(FileBlockUtil.class);
			fbu.checkFileBlocks();
			final String tfPath = ConfigureReader.instance().getTemporaryfilePath();
			final File f = new File(tfPath);
			if (!f.exists()) {
				f.mkdir();
			} else {
				final File[] listFiles = f.listFiles();
				for (final File fs : listFiles) {
					fs.delete();
				}
			}
			Printer.instance.print("校对完成。");
		} else {
			Printer.instance.print(
					"错误：文件系统节点信息校对失败，存储位置无法读写或不存在。");
		}
	}

	public void contextDestroyed(final ServletContextEvent sce) {
		Printer.instance.print("清理临时文件...");
		final String tfPath = ConfigureReader.instance().getTemporaryfilePath();
		final File f = new File(tfPath);
		final File[] listFiles = f.listFiles();
		for (final File fs : listFiles) {
			fs.delete();
		}
	}
}
